﻿using System;
using System.Threading;

/// <summary>
/// 使用事件机制，模拟实现一个闹钟功能。
/// 闹钟可以有嘀嗒（Tick）事件和响铃（Alarm）两个事件。在闹钟嘀嗒运行时或者响铃时，在控制台显示提示信息。
/// </summary>
namespace timeclock
{
    public delegate void TickHandler(object clock, TimeEventArgs timeInfo);
    public delegate void AlarmHandler(object clock);

    public class TimeEventArgs : EventArgs
    {
        public DateTime Time { get; set; }
    }

    public class Clock
    {
        public event TickHandler Tick;
        public event AlarmHandler Alarm;
        public DateTime AlarmTime { get; set; }

        public void Start()
        {
            while (true)
            {
                // 触发嘀嗒事件
                Tick(this, new TimeEventArgs { Time = DateTime.Now });
                //Tick?.Invoke(this, new TimeEventArgs { Time = DateTime.Now });

                if (DateTime.Now >= AlarmTime)
                {
                    //Alarm?.Invoke(this, EventArgs.Empty);
                    Alarm(this);
                    break;
                }

                Thread.Sleep(2000);
            }
        }

    }
    class Program
    {
        static void Main()
        {
            Clock clock = new Clock();

            clock.AlarmTime = DateTime.Now.AddSeconds(8);

            clock.Tick += (sender, e) =>
            {
                Console.WriteLine($"Tick: {e.Time.ToLongTimeString()}");
            };

            clock.Alarm += (sender) =>
            {
                Console.WriteLine("Alarm: The alarm clock is ringing!");
            };

            clock.Start();
        }
    }
}
